/**
 * Created by Administrator on 2017/5/25.
 */

var DBFactory = require('../db/mysql_db');
var adminDao = module.exports;

adminDao.login = function(data, cb){
    if(!data){
        cb(new Error(500));
        return;
    }
    DBFactory.poolQuery('select * from admin where account = ? ',[data.account],
        function () {
            cb('no connection');
        },
        function(err, result){
            if(err){
                cb(err);
                console.log(err);
                return;
            }
            if(result[0]){
                if(result[0]['password'] == data.password){
                    // console.log('success');
                    if (result[0].status == 0) {
                        cb('该账号已被禁用');
                        return;
                    }
                    cb(null,result[0]);
                }else {
                    cb('密码或账号不正确');
                }
            }else {
                // cb('不存在此用户');
                cb('密码或账号不正确');
            }
        }
    );
}

adminDao.resetPwd = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        var sql = 'update admin set password = ? ,updated_date = CURRENT_TIMESTAMP';
        var sqlValue = [data.password];
        sql += ' where uid = ?';
        sqlValue.push(data.adm_uid);
        DBFactory.poolQuery(sql,
            sqlValue,
            function () {
                cb("no connection");
            },
            function (err, result) {
                if (err) {
                    cb('密码重置失败！');
                    console.log(err);
                    return;
                }
                else if (result) {
                    cb(null, result);
                }
            });
    }
}

adminDao.isPassword = function (data, cb) {
    if (!data) {
        cb(new Error(500));
    } else {
        //获取用户的密码
        var sql = 'select * from admin where uid = ? ';
        DBFactory.poolQuery(sql, [data.adm_uid],
            function () {
                cb("no connection");
            },
            function (err, result) {
                if (err) {
                    cb(err);
                    console.log(err);
                    return;
                }
                if (result[0]) {
                    if (result[0].password == data.oldpassword) {
                        cb(null, result[0]);
                    } else {
                        cb('密码或账号不正确', result[0]);
                    }
                } else {
                    cb('不存在此用户');
                }
            });
    }
}